<!doctype html>
<html>
<head>
</head>
<body>

<script type="text/javascript">
var ws;
var url;

function connect() {
    url = document.getElementById("server_url").value;
    console.log(url);
    
    if ("WebSocket" in window) {
        ws = new WebSocket(url);
    } else if ("MozWebSocket" in window) {
        ws = new MozWebSocket(url);
    } else {
        document.getElementById("messages").innerHTML += "This Browser does not support WebSockets<br />";
        return;
    }
    ws.onopen = function(e) {
        document.getElementById("messages").innerHTML += "Client: A connection to "+ws.URL+" has been opened.<br />";
        
        document.getElementById("server_url").disabled = true;
        document.getElementById("toggle_connect").innerHTML = "Disconnect";
    };
    
    ws.onerror = function(e) {
        document.getElementById("messages").innerHTML += "Client: An error occured, see console log for more details.<br />";
        console.log(e);
    };
    
    ws.onclose = function(e) {
        document.getElementById("messages").innerHTML += "Client: The connection to "+url+" was closed.<br />";
    };
    
    ws.onmessage = function(e) {
        document.getElementById("messages").innerHTML += "Server: "+e.data+"<br />";
    };
}

function disconnect() {
    ws.close();
    document.getElementById("server_url").disabled = false;
    document.getElementById("toggle_connect").innerHTML = "Connect";
}

function toggle_connect() {
    if (document.getElementById("server_url").disabled === false) {
        connect();
    } else {
        disconnect();
    }
}

function send() {
    if (ws === undefined || ws.readyState != 1) {
        document.getElementById("messages").innerHTML += "Client: Websocket is not avaliable for writing<br />";
        return;
    }
    
    ws.send(document.getElementById("msg").value);
    document.getElementById("msg").value = "";
}

</script>

<style>
body,html {
    margin: 0px;
    padding: 0px;
}
#controls {
    float:right;
    background-color: #999;
}

</style>

<div id="controls">
    <div id="server">
    <input type="text" name="server_url" id="server_url" value="ws://localhost:5000" />
    <button id="toggle_connect" onclick="toggle_connect();">Connect</button>
    </div>

    <div id="message_input"><input type="text" name="msg" id="msg" value="Hello World!" />
    <button onclick="send();">Send</button></div>
</div>
<div id="messages"></div>

</body>
</html>